import numpy as np
import matplotlib.pyplot as plt

x = np.array([0.5, 0.6, 0.8, 1.1, 1.4])
y = np.array([5.0, 5.5, 6.0, 6.8, 7.2])
# 散点图
# plt.scatter(x, y)
#
# plt.grid(linestyle=":")
# plt.show()

# 实现梯度下降
## : y = w1*x + w0
w1 = 1  # 常用初始值为1
w0 = 1  # 常用初始值为1或0
learn_rate = 0.01  # 学习率，不能设太大
epoch = 200  # 训练轮数
w1s=[]
w0s=[]
losss=[]
epochs=[]
for i in range(epoch):
    loss = ((w1 * x + w0 - y) ** 2).sum() /2
    print("epoch:{:3},w1:{:.8f},w0:{:.8f},loss:{:.8f}".format(
        i + 1, w1, w0, loss
    ))
    w1s.append(w1)
    w0s.append(w0)
    losss.append(loss)
    epochs.append(i+1)
    d0 = (w0 + w1 * x - y).sum()
    d1 = (x * (w1 * x + w0 - y)).sum()
    w0 = w0 - learn_rate * d0
    w1 = w1 - learn_rate * d1
pred_y = w1 * x + w0
# plt.plot(x, pred_y)
#
# plt.grid(linestyle=":")
# plt.show()
plt.figure('Training params')
plt.subplot(3,1,1)
plt.plot(epochs,w0s,color='dodgerblue',label='w0')
plt.grid(linestyle=":")
plt.legend()

plt.subplot(3,1,2)
plt.plot(epochs,w1s,color='dodgerblue',label='w1')
plt.grid(linestyle=":")
plt.legend()

plt.subplot(3,1,3)
plt.plot(epochs,losss,color='dodgerblue',label='loss')
plt.grid(linestyle=":")
plt.legend()



plt.show()